package service

import (
	"fresh-food/model"
	"fresh-food/request"
	"fresh-food/response"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/jjl309/oneGroup"
)

func OrderAdd(c *gin.Context) {
	var data request.OrderAddRequest
	if err := c.ShouldBind(&data); err != nil {
		response.CurrencyErrResponse(c, err.Error(), 101)
		return
	}
	var freshFood model.FreshFood
	err := freshFood.GetFreshFoodInfoById(data.FreshFoodId)
	if err != nil {
		response.CurrencyErrResponse(c, err.Error(), -1)
		return
	}
	if freshFood.ID == 0 || freshFood.Stock < data.Num {
		response.CurrencyErrResponse(c, "库存不足", -1)
		return
	}
	totalPrice := freshFood.Price * float64(data.Num)
	tx := oneGroup.DB.Begin()
	order := model.Order{
		OrderId:     uuid.New().String(),
		FreshFoodId: data.FreshFoodId,
		Num:         data.Num,
		TotalPrice:  totalPrice,
		UserId:      1, //模拟写死 实际token获取
	}
	err = order.Create()
	if err != nil {
		tx.Rollback()
		response.CurrencyErrResponse(c, err.Error(), -1)
		return
	}
	err = freshFood.UpdateStockById(data.Num)
	if err != nil {
		tx.Rollback()
		response.CurrencyErrResponse(c, err.Error(), -1)
		return
	}
	tx.Commit()
	response.CurrencySuccessResponse(c, "下单成功", map[string]interface{}{"orderId": order.OrderId})
}
